<!--
 * @Description 新增角色
-->
<template>
  <el-dialog
    :title="dialogData.title"
    :visible.sync="dialogData.show"
    :before-close="handleClose"
    width="46%"
    class="dialog"
  >
    <el-form
      ref="roleInfoForm"
      label-position="top"
      :model="roleInfoForm"
      :rules="rules"
      label-width="85px"
    >
      <el-form-item label="角色名称：" prop="roleName">
        <el-input
          class="input-area"
          v-model="roleInfoForm.roleName"
          placeholder="请输入员工名称"
          maxlength="64"
        ></el-input>
      </el-form-item>
      <el-form-item label="角色权限：" prop="menuIds" class="is-required">
        <el-tree
          ref="tree"
          :data="roleInfoForm.treeData"
          :default-checked-keys="roleInfoForm.menuIds"
          show-checkbox
          default-expand-all
          :check-strictly="false"
          check-on-click-node
          node-key="id"
          :props="defaultProps"
          @check-change="powerCheckChange"
          :expand-on-click-node="false"
        ></el-tree>
        <div style="margin-top: 10px">
          <a @click="handleChooseAllTree">全选</a>
          <a style="margin-left: 16px" @click="handleClearAllTree">全否</a>
        </div>
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入备注"
          v-model="roleInfoForm.remark"
          maxlength="100"
          show-word-limit
          resize="none"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button
        size="small"
        type="primary"
        @click="handleConfirm"
        v-preventReClick
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
//请求
import { createRole, editRole } from "@/api/staff_role";

export default {
  components: {},
  props: {
    dialogData: {
      type: Object,
    },
  },
  data() {
    return {
      defaultProps: {
        children: "childNodeList",
        label: "menuName",
      },
      roleInfoForm: {
        roleName: "",
        menuIds: [],
        remark: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
        remark: [
          { required: true, message: "请输入备注内容", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    "dialogData.show": {
      immediate: true,
      handler: function (val, oldVal) {
        if (val) {
          this.$nextTick(() => {
            if (this.dialogData.type == "EDIT") {
              this.roleInfoForm = JSON.parse(JSON.stringify(this.dialogData));
              this.roleInfoForm.menuIds = this.roleInfoForm.bindMenuIds;
            } else {
              this.roleInfoForm = {
                roleName: "",
                menuIds: [],
                remark: "",
              };
            }
            this.roleInfoForm.treeData = JSON.parse(
              JSON.stringify(this.dialogData.treeData)
            );
            //这里的操作是为了反显选中的时候,父节点半选时不被选中
            let newTreeData = JSON.parse(
              JSON.stringify(this.dialogData.treeData)
            );
            newTreeData.forEach((item, index) => {
              item.disabled = true;
              if (item.childNodeList.length > 0) {
                item.childNodeList.forEach((cItem, cIndex) => {
                  cItem.disabled = true;
                });
              }
            });
            this.roleInfoForm.treeData = newTreeData;
            this.$refs.tree.setCheckedKeys(this.roleInfoForm.menuIds);
            //恢复权限树为可选状态
            this.$nextTick(() => {
              newTreeData.forEach((item, index) => {
                item.disabled = false;
                if (item.childNodeList.length > 0) {
                  item.childNodeList.forEach((cItem, cIndex) => {
                    cItem.disabled = false;
                  });
                }
              });
              this.roleInfoForm.treeData = newTreeData;
            });
            this.$refs.roleInfoForm.resetFields();
          });
        }
      },
    },
  },
  methods: {
    //全选
    handleChooseAllTree() {
      let allMenuIds = this.getMenuIds(this.roleInfoForm.treeData);
      this.roleInfoForm.menuIds = allMenuIds;
      this.$refs.tree.setCheckedKeys(allMenuIds);
    },

    //递归获取所有权限id 并组成数组
    getMenuIds(arr) {
      let newArr = [];
      arr.forEach((item) => {
        newArr.push(item.id);
        if (Array.isArray(item.childNodeList)) {
          newArr.push(...this.getMenuIds(item.childNodeList));
        }
      });
      return newArr;
    },

    //全否
    handleClearAllTree() {
      this.roleInfoForm.menuIds = [];
      this.$refs.tree.setCheckedKeys([]);
    },

    //保存修改
    handleConfirm() {
      this.$refs.roleInfoForm.validate((valid) => {
        if (valid) {
          if (this.dialogData.type == "ADD") {
            // console.log("keys->", this.$refs.tree.getCheckedKeys());
            this.roleInfoForm.menuIds = this.$refs.tree.getCheckedKeys();
          }
          //校验通过
          if (this.roleInfoForm.menuIds.length == 0) {
            this.$message({
              message: "请至少勾选一个菜单权限",
              type: "warning",
            });
            return;
          }
          switch (this.dialogData.type) {
            case "ADD": {
              this.handleCreate();
              break;
            }
            case "EDIT": {
              this.handleEdit();
              break;
            }
          }
        }
      });
    },
    //创建新角色
    handleCreate() {
      createRole(this.roleInfoForm)
        .then((res) => {
          this.$message({
            message: "创建成功",
            type: "success",
          });
          this.$emit("dialogConfirm");
          this.dialogData.show = false;
        })
        .catch(() => {});
    },
    //编辑角色
    handleEdit() {
      let params = {
        ...this.roleInfoForm,
      };
      editRole(params)
        .then((res) => {
          this.$message({
            message: "编辑成功",
            type: "success",
          });
          this.$emit("dialogConfirm");
          this.dialogData.show = false;
        })
        .catch(() => {});
    },

    //关闭弹窗
    handleClose() {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.dialogData.show = false;
        })
        .catch((_) => {});
    },

    //权限选中状态变更  注意，当选中子节点的时候,由于父也会被选中，所以会反复触发
    powerCheckChange(data, checked, indeterminate) {
      // console.log("######");
      if (this.dialogData.type == "EDIT") {
        this.$nextTick(() => {
          let chooseNodesArr = this.$refs.tree.getCheckedNodes(false, true);
          let keysArr = [];
          chooseNodesArr.forEach((item, index) => {
            keysArr.push(item.id);
          });
          this.roleInfoForm.menuIds = keysArr;
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  a {
    color: #409eff;
  }
}

.el-form-item {
  margin-bottom: 10px;
}

::v-deep {
  .el-dialog__body {
    padding: 10px 20px;
  }
}

.input-area {
  width: 100%;
}

.el-tree {
  height: 320px;
  overflow: scroll;
  border: 1px solid #999999;
}
</style>
